import fs from 'fs'
import { resolve } from 'path'
import glob from 'fast-glob'
import chalk from 'chalk'

const step = (text, color) => console.log(chalk[color](text))

async function parsePackageJsonFiles(filePaths) {
  const jsonList = []
  for (const i of filePaths) {
    try {
      const content = await fs.readFileSync(i, 'utf8')
      const jsonContent = JSON.parse(content)
      const { description, main, author, config } = jsonContent
      jsonList.push({
        originPath: i,
        filePaths: i.replace('packages/', '').replace('package.json', main.replace('ts', 'js')),
        timestamp: Date.now(),
        content: {
          description,
          author,
          ...config
        }
      })
    } catch (error) {
      jsonList.push({
        originPath: i,
        filePaths: i,
        timestamp: Date.now(),
        content: null,
        error: error.message
      })
    }
  }
  return jsonList
}

const collectionDirInfo = async dir => {
  const outPath = resolve('dist/' + dir)
  const files = await glob(`packages/${dir}/**/package.json`, { onlyFiles: true })
  const res = await parsePackageJsonFiles(files)
  return new Promise(r => {
    fs.stat(outPath, async err => {
      if (err) {
        await fs.mkdirSync(outPath)
      }
      await fs.writeFileSync(outPath + '/config.json', JSON.stringify(res, null, 2))
      r()
    })
  })
}

export default collectionDirInfo
